package ru.JDiskCatalog.ui;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Path2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileFilter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JButton;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;

import ru.JDiskCatalog.util.SqlUtil;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class PopulateCatalogDlg extends javax.swing.JDialog {
	private JTextArea ctlCurrentPath;
	private JButton ctlCancel;
	private int m_nMediaID;
	private PopulateCatalogTask _PopulateTask;
	private Connection m_objConnection;
	
	/**
	* Auto-generated main method to display this JDialog
	*/
		
	public PopulateCatalogDlg(JFrame frame,int MediaID,Connection objConnection) {
		super(frame);
		m_objConnection=objConnection;
		m_nMediaID=MediaID;
		initGUI();
		RunBackgroundTask();
	}
	
	private void initGUI() {
		try {
			{
				getContentPane().setLayout(null);
				this.setModal(true);
				this.setResizable(false);
				this.setTitle("Populate catalog");
			}
			{
				ctlCurrentPath = new JTextArea();
				getContentPane().add(ctlCurrentPath, "Center");
				ctlCurrentPath.setBounds(5, 0, 377, 51);
				ctlCurrentPath.setEditable(false);
				ctlCurrentPath.setLineWrap(true);
			}
			{
				ctlCancel = new JButton();
				getContentPane().add(ctlCancel);
				ctlCancel.setText("Cancel");
				ctlCancel.setBounds(132, 57, 109, 22);
				ctlCancel.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						ctlCancelActionPerformed(evt);
					}
				});
			}
			

			this.setSize(388, 126);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void RunBackgroundTask()
	{			
		_PopulateTask=new PopulateCatalogTask(m_nMediaID,ctlCurrentPath);
		_PopulateTask.addPropertyChangeListener(new PropertyChangeListener() {
			@Override
			public void propertyChange(PropertyChangeEvent evt) {             
	             if ("state".equals(evt.getPropertyName())
	                     && SwingWorker.StateValue.DONE == evt.getNewValue()) {
	                 	setVisible(false);
	             }
			} 						
		});
		
		_PopulateTask.execute();	
	}
	
	private void ctlCancelActionPerformed(ActionEvent evt) {
		_PopulateTask.cancel(true);
		setVisible(false);
	}

	class PopulateCatalogTask extends SwingWorker<Object,String>
	{
		private int m_nMediaID;
		private JTextArea m_ctlCurrentPath;
		
		public PopulateCatalogTask(int MediaID,JTextArea ctlCurrentPath)
		{
			m_nMediaID=MediaID;
			m_ctlCurrentPath=ctlCurrentPath;
		}
		
		@Override
		protected Object doInBackground() throws Exception {			
			PreparedStatement ps=null;
			ResultSet rs=null;		
			PreparedStatement psAddFile=null;
			PreparedStatement psAddDirectory=null;
			
			String strPath="";
			
			try
			{
				ps=m_objConnection.prepareStatement("SELECT \"PATH\" FROM MEDIA WHERE MEDIA_ID=?");
				psAddDirectory=m_objConnection.prepareStatement("INSERT INTO DIRECTORIES(MEDIA_ID,PARENT_ID,\"NAME\",\"PATH\") VALUES(?,?,?,?)");
				psAddFile=m_objConnection.prepareStatement("INSERT INTO FILES(DIRECTORY_ID,\"NAME\",\"EXTENSION\",\"SIZE\",\"DATECREATED\") VALUES(?,?,?,?,?)");

				ps.setInt(1, m_nMediaID);
				rs=ps.executeQuery();
				if(rs.next())
				{										
					File objRootDir=new File(rs.getString("PATH"));
					if(objRootDir.exists() && objRootDir.isDirectory())
					{
						int DirectoryID=AddDirectory(0,objRootDir,psAddDirectory);
						ProcessDirectory(DirectoryID,objRootDir,psAddFile,psAddDirectory);
					}
				}
			}
			catch(SQLException sqle)
			{		
				SqlUtil.ReportSQLException(sqle);
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			finally
			{
				SqlUtil.CloseResultSet(rs);
				SqlUtil.ClosePreparedStatement(ps);
				SqlUtil.ClosePreparedStatement(psAddFile);
				SqlUtil.ClosePreparedStatement(psAddDirectory);
			}

			return null;
		}		
		
		//recursively process directories
		private void ProcessDirectory(int DirectoryID,File objDir,PreparedStatement psAddFile, PreparedStatement psAddDirectory) throws SQLException
		{		
			File[] arrFiles=objDir.listFiles();
			//перебрать. занести все файлы в базу
			//все папки добавить через рекурсию
			for(File objFile : arrFiles)
			{
				ctlCurrentPath.setText(objFile.getPath());
				
				if(objFile.isDirectory())
				{
					int NewDirectoryID=AddDirectory(DirectoryID,objFile,psAddDirectory);
					ProcessDirectory(NewDirectoryID,objFile,psAddFile,psAddDirectory);
				}
				
				if(objFile.isFile())
				{
					//занести в базу
					psAddFile.setInt(1,DirectoryID);
					psAddFile.setString(2, objFile.getName());
					psAddFile.setString(3, getFileExtension(objFile.getName()));
					psAddFile.setLong(4, objFile.length());
					psAddFile.setLong(5, objFile.lastModified());
					
					psAddFile.addBatch();
				}	
				
				if(isCancelled())
					return;
			}		
			
			psAddFile.executeBatch();
		}
		
		private int AddDirectory(int ParentID,File objDir,PreparedStatement psAddDirectory) throws SQLException
		{
			//занести в базу
			psAddDirectory.setInt(1,m_nMediaID);
			
			if(ParentID==0)
				psAddDirectory.setNull(2, java.sql.Types.INTEGER);
			else
				psAddDirectory.setInt(2,ParentID);
			
			psAddDirectory.setString(3, objDir.getName());
			psAddDirectory.setString(4,objDir.getPath());
			psAddDirectory.execute();					
			//вытащить первичный ключ
			int NewDirectoryID=0;
			Statement sGetIdentity=null;
			ResultSet rsGetIdentity=null;
			try
			{
				sGetIdentity=m_objConnection.createStatement();
				rsGetIdentity=sGetIdentity.executeQuery("SELECT IDENTITY_VAL_LOCAL() FROM DIRECTORIES");
				if(rsGetIdentity.next())
					NewDirectoryID=rsGetIdentity.getInt(1);
			}
			catch(SQLException sqle)
			{		
				SqlUtil.ReportSQLException(sqle);
			}		
			finally
			{
				SqlUtil.CloseResultSet(rsGetIdentity);
				SqlUtil.CloseStatement(sGetIdentity);
			}
			
			return NewDirectoryID;
		}
		
		private String getFileExtension(String strFullName)
		{
			String[] tokens = strFullName.split("\\.(?=[^\\.]+$)");
			return tokens.length>1 ? tokens[1] : "";
		}
	}
}
